<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\web\controller;

use app\common\model\User as UserModel;

class Base
{
    protected $request;
    protected $user_id = 0;
    protected $user = null;
    protected $limit = 18;

    public function __construct()
    {
        $this->request = request();
        $this->limit   = $this->request->get('limit', 18);



        // 尝试获取用户信息（不强制登录）
        try {
            // 使用Webman推荐的session获取方式
            $session = $this->request->session();
            $userId  = $session->get('user_id');

            if ($userId) {
                // 检查session是否过期
                $expireTime = $session->get('expire_time');
                if ($expireTime && $expireTime < time()) {
                    // session已过期，清除
                    $session->flush();
                    $this->user_id = 0;
                    $this->user    = null;
                } else {
                    $this->user    = UserModel::where([
                        'id'     => $userId,
                        'status' => 1
                    ])->find();
                    $this->user_id = $this->user ? $this->user->id : 0;
                }
            } else {
                $this->user_id = 0;
                $this->user    = null;
            }
        } catch (\Exception $e) {
            $this->user_id = 0;
            $this->user    = null;
        }
    }

    /**
     * 渲染模板
     * @param string $template 模板文件名
     * @param array $data 模板变量
     * @return \support\Response
     */
    protected function render($template, $data = [])
    {
        // 添加全局模板变量
        $globalData = [
            'user'           => $this->user,
            'user_id'        => $this->user_id,
            'is_login'       => $this->user_id > 0,
            // 静态css js版本号,开启开发模式是 是 time() 否则是 conf('static_version')
            'static_version' => conf('app_development') ? time() : conf('static_version'),
        ];

        // 合并数据
        $data = array_merge($globalData, $data);

        // 设置页面标题
        if (!isset($data['title'])) {
            $data['title'] = conf('site_subtitle') . ' - ' . conf('site_name');
        } else {
            $data['title'] = $data['title'] . ' - ' . conf('site_name');
        }

        // 设置SEO信息
        if (!isset($data['keywords'])) {
            $data['keywords'] = conf('site_keywords');
        }
        if (!isset($data['description'])) {
            $data['description'] = conf('site_desc');
        }

        // 获取正确的模板路径
        $templatePath = $this->getTemplatePath($template);

        return view($templatePath, $data);
    }

    /**
     * 获取当前模板名称
     */
    protected function getCurrentTemplate()
    {
        return config('site.theme.template', 'default');
    }

    /**
     * 获取模板路径
     */
    protected function getTemplatePath($view)
    {
        $template = $this->getCurrentTemplate();

        // 所有模板都在templates目录下，包括default
        $templatePath = "{$template}/{$view}";

        // 检查模板文件是否存在
        $fullPath = base_path() . "/app/web/view/{$templatePath}.html";
        if (!file_exists($fullPath)) {
            throw new \Exception("模板文件不存在: {$templatePath}.html");
        }
        return $templatePath;
    }

    /**
     * 返回JSON响应
     * @param int $code
     * @param string $msg
     * @param mixed $data
     * @return \support\Response
     */
    protected function json($code = 1, $msg = '', $data = '')
    {
        $result = [
            'code' => $code,
            'msg'  => $msg ?: ($code ? '操作成功' : '操作失败'),
            'data' => $data,
            'time' => time(),
        ];
        return json($result);
    }

    /**
     * 成功响应
     * @param string $msg
     * @param mixed $data
     * @return \support\Response
     */
    protected function success($msg = '', $data = '')
    {
        return $this->json(1, $msg, $data);
    }

    /**
     * 错误响应
     * @param string $msg
     * @param mixed $data
     * @return \support\Response
     */
    protected function error($msg = '', $data = '')
    {
        return $this->json(0, $msg, $data);
    }


    /**
     * 获取当前用户信息（AJAX接口）
     * @return \support\Response
     */
    public function getUserInfo()
    {
        if ($this->user_id > 0 && $this->user) {
            return $this->success('获取成功', [
                'id'          => $this->user->id,
                'username'    => $this->user->username,
                'email'       => $this->user->email,
                'avatar'      => $this->user->avatar,
                'is_vip'      => $this->user->is_vip,
                'points'      => $this->user->points,
                'level'       => $this->user->level ?? 1,
                'create_time' => $this->user->create_time,
            ]);
        } else {
            return $this->error('未登录');
        }
    }
}
